package cn.stronglink.oil.map;

import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.support.annotation.IdRes;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.RadioGroup;
import android.widget.Toast;

import com.baidu.mapapi.map.MapView;

import java.io.IOException;
import java.util.List;
import java.util.concurrent.TimeoutException;

import cn.stronglink.oil.R;
import cn.stronglink.oil.entity.DeviceAlarmInfo;
import cn.stronglink.oil.entity.DeviceRealTimeInfo;
import cn.stronglink.oil.mq.DeviceGasDataManager;
import cn.stronglink.oil.mq.IDeviceGasDataListener;
import cn.stronglink.oil.mq.IMqListener;
import cn.stronglink.oil.mq.MqMessageReceiverClient;
import cn.stronglink.oil.user.UserInfo;
import cn.stronglink.oil.utils.PermissionsChecker;
import cn.stronglink.oil.widget.EasingType;
import cn.stronglink.oil.widget.ExpoInterpolator;
import cn.stronglink.oil.widget.Panel;


public class BaiduMapActivity extends Activity implements IMapViewOverlyListener, IDeviceGasDataListener, Panel.OnPanelListener,
        RadioGroup.OnCheckedChangeListener, View.OnClickListener {
    MapView mapView = null;
    private MapViewOverlay mapViewOverlay;//地图覆盖物
    private MapViewSDKReceiver mapViewSDKReceiver;//地图广播接收器
    private DeviceInfoView deviceInfoView;//传感器数据显示
    private DeviceGasDataManager deviceGasDataManager;//服务器端数据
    private DeviceInfoPresenter presenter;
    private RadioGroup rg_filter;
    private ImageView iv_search;
    private Panel panel;
    private static final int REQUEST_CODE = 1; // 请求码
    // 所需的全部权限
    static final String[] PERMISSIONS = new String[]{
            Manifest.permission.ACCESS_COARSE_LOCATION,
            Manifest.permission.ACCESS_FINE_LOCATION,
            Manifest.permission.READ_PHONE_STATE,
            Manifest.permission.WRITE_EXTERNAL_STORAGE
    };
    private PermissionsChecker mPermissionsChecker; // 权限检测器

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_baidu_map);
        mapViewSDKReceiver = new MapViewSDKReceiver(this);
        mapViewSDKReceiver.regisger();
        initViewAndData();
    }

    private void initViewAndData() {
        mPermissionsChecker = new PermissionsChecker(this);
        // 缺少权限时, 进入权限配置页面
        if (mPermissionsChecker.lacksPermissions(PERMISSIONS)) {
            startPermissionsActivity();
        }

        //地图初始化
        mapView = (MapView) findViewById(R.id.mv_oil);
        mapViewOverlay = new MapViewOverlay(this, mapView);
        mapViewOverlay.setMapViewOverlyListener(this);
        deviceInfoView = new DeviceInfoView(this);

        //初始化客户端
        if (UserInfo.getInstance() == null) return;
        deviceGasDataManager = new DeviceGasDataManager();
        deviceGasDataManager.setDeviceGasDataListener(this);

        presenter = new DeviceInfoPresenter(this, deviceInfoView);

        //右侧抽屉--设备历史数据
        panel = (Panel) findViewById(R.id.rightPanel);
        panel.setOnPanelListener(this);
        panel.setInterpolator(new ExpoInterpolator(EasingType.Type.OUT));

        rg_filter = (RadioGroup) findViewById(R.id.rg_filter);
        rg_filter.setOnCheckedChangeListener(this);
        iv_search = (ImageView) findViewById(R.id.iv_search);
        iv_search.setOnClickListener(this);
    }

    private void startPermissionsActivity() {
        ActivityCompat.requestPermissions(this, PERMISSIONS, REQUEST_CODE);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode) {
            case REQUEST_CODE: {
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    //权限开启成功
                } else {
                    //权限开启失败 显示提示信息
                    deviceInfoView.showExcepitionMsg(getResources().getString(R.string.permission_deny));
                }
                break;
            }
        }
    }


    @Override
    protected void onResume() {
        super.onResume();
        mapView.onResume();
    }

    @Override
    protected void onStart() {
        super.onStart();

    }

    @Override
    protected void onPause() {
        super.onPause();
        mapView.onPause();
    }

    @Override
    protected void onStop() {
        super.onStop();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        try {
            if (deviceGasDataManager != null) {
                deviceGasDataManager.close();
                deviceGasDataManager.setDeviceGasDataListener(null);
                deviceGasDataManager = null;
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        mapViewSDKReceiver.unRegisterReceiver();
        mapView.onDestroy();
        mapViewOverlay.clearOverlay();
    }

    @Override
    public void onClickDevice(DeviceRealTimeInfo.GasDevicesBean deviceInfo) {
        deviceInfoView.showDeviceView();
        deviceInfoView.clearDeviceInfo();
        deviceInfoView.showDeviceInfo(deviceInfo);
    }

    @Override
    public void onClickAlarmDevice(DeviceAlarmInfo alarmInfo) {
        deviceInfoView.showDeviceView();
        deviceInfoView.clearDeviceInfo();
        deviceInfoView.showAlarmInfo(alarmInfo);
    }

    @Override
    public void onMqConnect() {
        Log.i("mq", "通讯onConnect");
    }

    @Override
    public void onMqDisConnect() {
        Log.i("mq", "通讯onDisConnect");
    }

    @Override
    public void onRecRealTimeData(final DeviceRealTimeInfo realTimeInfo) {
        if (realTimeInfo != null && realTimeInfo.getGasDevices() != null) {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    //显示气象
                    deviceInfoView.showClimateInfo(realTimeInfo.getWeatherDevice());
                    //添加设备及设备实时信息
                    List<DeviceRealTimeInfo.GasDevicesBean> gasDevicesBeenList = realTimeInfo.getGasDevices();
                    mapViewOverlay.clearOverlay();
                    for (DeviceRealTimeInfo.GasDevicesBean gasDevicesBean : gasDevicesBeenList) {
                        mapViewOverlay.setOverlay(gasDevicesBean);
                    }
                    deviceInfoView.addRealTimeData(realTimeInfo);
                }
            });
        }
    }

    @Override
    public void onRecAlarmData(final DeviceAlarmInfo deviceAlarmInfo) {
        if (deviceAlarmInfo != null) {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    mapViewOverlay.setOverlay(deviceAlarmInfo);
                }
            });
        }
    }


    @Override
    public void onPanelClosed(Panel panel) {
        //抽屉关闭
    }

    @Override
    public void onPanelOpened(Panel panel) {
        //抽屉打开
        presenter.getHistoryInfo(null, 0, 0);
    }

    @Override
    public void onCheckedChanged(RadioGroup group, @IdRes int checkedId) {
        switch (checkedId) {
            case R.id.rb_gas_type:
                //气体类型
                deviceInfoView.hideHistoryView();
                deviceInfoView.showFilterGasTypeView();
                presenter.getGasType();
                break;
            case R.id.rb_device_number:
                //设备id
                deviceInfoView.hideHistoryView();
                deviceInfoView.showFilterDeviceIdView();
                break;
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_search:
                rg_filter.clearCheck();
                deviceInfoView.clearHistoryData();
                deviceInfoView.hideFilterView();
                deviceInfoView.showHistoryView();
                String selectedDevice = deviceInfoView.getSelectedDeviceId();
                int selectedDeviceId = -1;
                if (selectedDevice != null) {
                    if (selectedDevice.contains(getResources().getString(R.string.all))) {
                        selectedDeviceId = -1;
                    } else {
                        selectedDeviceId = Integer.valueOf(selectedDevice);
                    }
                }
                int gasType = deviceInfoView.getSelectedGasType();
                deviceInfoView.setDeviceId(selectedDeviceId);
                deviceInfoView.setGasTypeIndex(gasType);
                presenter.getSelectedHistory(gasType, selectedDeviceId);
                break;
            case R.id.btn_syn:
                Toast.makeText(BaiduMapActivity.this, "同步窗体", Toast.LENGTH_LONG).show();
                Intent intent = new Intent(this, SynchronizeActivity.class);
                startActivity(intent);
                break;
        }
    }

    @Override
    public void onBackPressed() {
        if (panel.isOpen()) {
            panel.setOpen(!panel.isOpen(), true);
        } else {
            super.onBackPressed();
            finish();
        }
    }
}
